/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tixian.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.cashcharge.entity.CashCharge;
import com.jeeplus.modules.cashcharge.service.CashChargeService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.recharge.entity.Recharge;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tixian.entity.Tixian;
import com.jeeplus.modules.tixian.service.TixianService;

/**
 * 用户提现记录Controller
 * @author freedom
 * @version 2020-08-07
 */
@Controller
@RequestMapping(value = "${adminPath}/tixian/tixian")
public class TixianController extends BaseController {

	@Autowired
	private TixianService tixianService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private CashChargeService cashChargeService;
	@Autowired
	private MemberService memberService;
	
	@ModelAttribute
	public Tixian get(@RequestParam(required=false) String id) {
		Tixian entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tixianService.get(id);
		}
		if (entity == null){
			entity = new Tixian();
		}
		return entity;
	}
	
	/**
	 * 用户提现记录列表页面
	 */
	@RequiresPermissions("tixian:tixian:list")
	@RequestMapping(value = {"list", ""})
	public String list(Tixian tixian, Model model) {
		model.addAttribute("tixian", tixian);
		return "modules/tixian/tixianList";
	}
	
		/**
	 * 用户提现记录列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Tixian tixian, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Tixian> page = tixianService.findPage(new Page<Tixian>(request, response), tixian); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑用户提现记录表单页面
	 */
	@RequiresPermissions(value={"tixian:tixian:view","tixian:tixian:add","tixian:tixian:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, Tixian tixian, Model model) {
		model.addAttribute("tixian", tixian);
		model.addAttribute("mode", mode);
		return "modules/tixian/tixianForm";
	}

	/**
	 * 保存用户提现记录
	 */
	@ResponseBody
	@RequiresPermissions(value={"tixian:tixian:add","tixian:tixian:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Tixian tixian, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(tixian);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		tixianService.save(tixian);//保存
		j.setSuccess(true);
		j.setMsg("保存用户提现记录成功");
		return j;
	}
	
	/**
	 * 删除用户提现记录
	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Tixian tixian) {
		AjaxJson j = new AjaxJson();
		tixianService.delete(tixian);
		j.setMsg("删除用户提现记录成功");
		return j;
	}
	
	/**
	 * 批量删除用户提现记录
	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			tixianService.delete(tixianService.get(id));
		}
		j.setMsg("删除用户提现记录成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Tixian tixian, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "用户提现记录"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Tixian> page = tixianService.findPage(new Page<Tixian>(request, response, -1), tixian);
            List<Tixian> tixianList = page.getList();
			if (tixianList.size()>0){
				for (Tixian tixian1 : tixianList) {
					tixian1.setCashTime(DateUtils.formatDateTime(tixian1.getCreateDate()));
					tixian1.setExamineTime(DateUtils.formatDateTime(tixian1.getUpdateDate()));
				}
			}
    		new ExportExcel("用户提现记录", Tixian.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出用户提现记录记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Tixian> list = ei.getDataList(Tixian.class);
			for (Tixian tixian : list){
				try{
					tixianService.save(tixian);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户提现记录记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条用户提现记录记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入用户提现记录失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入用户提现记录数据模板
	 */
	@ResponseBody
	@RequiresPermissions("tixian:tixian:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "用户提现记录数据导入模板.xlsx";
    		List<Tixian> list = Lists.newArrayList(); 
    		new ExportExcel("用户提现记录数据", Tixian.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


	/**
	 * 确认提现
	 */
	@ResponseBody
	@RequestMapping(value = "confirmCashOut")
	public AjaxJson confirmCashOut(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			Tixian tixian = tixianService.get(id);
			if ("0".equals(tixian.getShenhe())){
				tixianService.confirmCash(tixian);
			}
		}
		j.setMsg("确认提现成功");
		return j;
	}


	/**
	 * 驳回提现
	 */
	@ResponseBody
	@RequestMapping(value = "returnCashOut")
	public AjaxJson returnCashOut(String ids) {
		AjaxJson j = new AjaxJson();
		List<CashCharge> cashCharges = cashChargeService.findAllList(new CashCharge());
		BigDecimal charge = BigDecimal.valueOf(cashCharges.get(0).getServiceCharge()).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN);
		String idArray[] =ids.split(",");
		for(String id : idArray){
			Tixian tixian = tixianService.get(id);
			if ("0".equals(tixian.getShenhe())){
				tixian.setShenhe("2");
				Account account = new Account();
				account.setMember(tixian.getMember());
				List<Account> accountList = accountService.findList(account);
				if (accountList.size()>0){
					BigDecimal money = BigDecimal.valueOf(accountList.get(0).getYue()).add(BigDecimal.valueOf(tixian.getMoney()));
					accountList.get(0).setYue(money.doubleValue());
					accountService.save(accountList.get(0));
				}
				tixianService.save(tixian);
			}
		}
		j.setMsg("驳回成功");
		return j;
	}

}